#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H

#include <Arduino.h>

template<typename T,uint32_t N>
class CircularBuffer
{
public:
// 创建环形缓冲区（实际可存储capacity个元素）
CircularBuffer():_size(N + 1),_head(0),_tail(0)
{

}
~CircularBuffer()=default;
// 判断缓冲区是否为空
bool empty() {
    return this->_head == this->_tail;
}
 
// 判断缓冲区是否已满
bool full() {
    return ((this->_head + 1) % this->_size) == this->_tail;
}
// 写入数据（覆盖旧数据模式）
void push(T data) {
    // 缓冲区满时覆盖最旧数据
    if (full()) {
        this->_tail = (this->_tail + 1) % this->_size; // 移动读指针丢弃旧数据
    }
    this->_buffer[this->_head] = data;
    this->_head = (this->_head + 1) % this->_size;
}
void reset()
{
    _head = 0;
    _tail = 0;
}
bool peek(T &data) {
    if (empty()) return false; // 缓冲区空
    data = this->_buffer[this->_tail];
    return true;
}
// 读取数据（返回是否成功）
bool pop(T &data) {
    if (empty()) return false; // 缓冲区空
    data = this->_buffer[this->_tail];
    this->_tail = (this->_tail + 1) % this->_size;
    return true;
}

uint32_t size()
{
    uint32_t elements;
    if (!this->full()) {
        if (_head < _tail) {
            elements = (N) + _head - _tail;
        } else {
            elements = _head - _tail;
        }
    } else {
        elements =  (N);
    }
    return elements;
}
private:
    T _buffer[N+1];    // 缓冲区数组

    uint32_t _size;       // 缓冲区总容量（含预留位）
    uint32_t _head;       // 写指针
    uint32_t _tail;       // 读指针
};

#endif